import * as request from "request";
import { readFile } from "fs";

import config from "./../middleware/config";


/**
 * 转发服务
 */
export class forward {
    private static def = new forward();

    /*默认图片*/
    private async defImage(encoding: string) {
        const result: { body?: Buffer, contentType?: string } = {};
        return new Promise<any>((resolve) => {

            readFile(`${config.filePath.images}/default.png`, encoding, (err, data) => {
                if (err) {
                    // TODO: 默认照片的 binary
                    resolve({
                        body: new Buffer('', encoding),
                        contentType: 'image/png'
                    });
                } else {
                    resolve({
                        body: new Buffer(data, encoding),
                        contentType: 'image/png'
                    });
                }
            });
        });
    };

    /**
     * 图片转发
     * @param _url 
     */
    static image(_url: string, encoding = 'binary') {
        return new Promise<{ body: Buffer, contentType: string }>((resolve, reject) => {
            request({
                url: _url,
                encoding: encoding
            }, async (error: any, resp: any, body: any) => {
                if (error) {
                    resolve(await this.def.defImage(encoding));
                }
                else {
                    resolve({
                        body: new Buffer(body, encoding),
                        contentType: resp.headers['content-type']
                    });
                }
            });
        });
    };

}